namespace ResumableDownload.View.Converters
{
    using System;
    using System.Globalization;
    using System.Windows;
    using System.Windows.Data;
    using WP7Contrib.Services.DownloadManager;

    public sealed class RequestDurationToStringConverter : IValueConverter
    {
        private const int MegaByte = 1048576;
        private const int GigaByte = 1073741824;

        public static NumberFormatInfo NumberFormatInfo;

        public readonly string DurationFormat = "Elapsed time: {0} ";
        
        static RequestDurationToStringConverter()
        {
            NumberFormatInfo = (NumberFormatInfo)CultureInfo.CurrentUICulture.NumberFormat.Clone();
            NumberFormatInfo.NumberDecimalDigits = 0;
        }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var request = value as FileRequest;

            if (request == null || value == DependencyProperty.UnsetValue)
            {
                return DependencyProperty.UnsetValue;
            }
            
            var duration = string.Empty;
            if (request.Duration.TotalSeconds < 60)
            {
                duration = request.Duration.TotalSeconds.ToString("N", NumberFormatInfo) + " secs";
            }
            else
            {
                if (request.Duration.TotalMinutes < 60)
                {
                    duration = request.Duration.Minutes.ToString("N", NumberFormatInfo) + " mins " + request.Duration.Seconds.ToString("N", NumberFormatInfo) + " secs";
                }
                else
                {
                    duration = request.Duration.Hours.ToString("N", NumberFormatInfo) + " hrs " + request.Duration.Minutes.ToString("N", NumberFormatInfo) + " mins";
                }
            }

            return string.Format(DurationFormat, duration);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return DependencyProperty.UnsetValue;
        }
    }
}